/**
 *
 */
package com.naiterui.ehp.bs.doctor.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.naiterui.ehp.bp.bo.doctor.DrDepartmentBO;
import com.naiterui.ehp.bp.domain.Department;
import com.naiterui.ehp.bs.doctor.dao.IDepartmentDao;
import com.naiterui.ehp.bs.doctor.service.IDepartmentService;
import com.naiterui.ehp.bs.doctor.vo.DepartmentCascadeVo;
import com.naiterui.ehp.bs.doctor.vo.DepartmentVo;

@Service
public class AdDepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private IDepartmentDao departmentDao;

    @Override
    public List<DepartmentCascadeVo> getCascadeDedepartmentList() {
        // 获取所有的部门列表信息
        List<Department> list = this.departmentDao.getDepartmentList();
        // 同一个父类进行放在要给key中
        Map<Integer, List<DepartmentVo>> map = new LinkedHashMap<>();
        // 根据id，存储当前部门信息
        Map<Integer, DepartmentVo> fstDepartMap = new LinkedHashMap<>();
        if (list != null && list.size() > 0) {
            for (Department dep : list) {
                DepartmentVo vo = new DepartmentVo();
                Integer id = dep.getId();
                vo.setDepartId(dep.getId());
                vo.setDepartName(dep.getName());
                int parentId = dep.getParentId();
                vo.setParentId(parentId);
                List<DepartmentVo> children = map.get(parentId);
                if (parentId != 0) {
                    if (children == null) {
                        children = new ArrayList<>();
                    }
                    children.add(vo);
                    map.put(parentId, children);
                } else {
                    fstDepartMap.put(id, vo);
                }
            }
        }

        // 使用程序进行二级关系处理
        List<DepartmentCascadeVo> result = new ArrayList<>();
        // 迭代父类id集合
        if (fstDepartMap.size() > 0) {
            for (Integer fstDeppartId : fstDepartMap.keySet()) {
                DepartmentVo depart = fstDepartMap.get(fstDeppartId);
                DepartmentCascadeVo vo = new DepartmentCascadeVo();
                vo.setDepartId(depart.getDepartId());
                vo.setDepartName(depart.getDepartName());
                vo.setSecondDepart(map.get(fstDeppartId));
                result.add(vo);
            }

        }
        return result;
    }

    @Override
    public DrDepartmentBO getDepartmentByName(String name) {
        Department department = departmentDao.getDepartmentByName(name);
        if (department == null) {
            return null;
        }
        return DrDepartmentBO.builder().id(department.getId()).name(department.getName()).build();
    }
}
